package com.uziot.bucket.eureka.config;

import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.StatusChangeEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author lenovl
 * 当注册中心客户端启动初始化时执行
 */
@Slf4j
@Component
public class EurekaInitNotify {
    ApplicationInfoManager.StatusChangeListener eurekaListener = null;
    @Resource
    private EurekaClient eurekaClient;

    private final ExecutorService executorService = Executors.newSingleThreadExecutor();

    @PostConstruct
    public void init() {
        eurekaListener = new ApplicationInfoManager.StatusChangeListener() {
            @Override
            public String getId() {
                return "forExample";
            }

            @Override
            public void notify(StatusChangeEvent statusChangeEvent) {
                // 当前状态为UP， 之前的状态为STARTING
                if (InstanceInfo.InstanceStatus.UP == statusChangeEvent.getStatus() &&
                        InstanceInfo.InstanceStatus.STARTING == statusChangeEvent.getPreviousStatus()) {
                    // 执行一遍之后，在卸载该监听，达到在EurekaClient启动完成之后，仅执行一次
                    // ID可以自定义
                    // 可定义轮询状态通知
                    log.info("当前状态为UP， 之前的状态为STARTING 执行一次该调用！");
                }
                executorService.execute(() -> {
                    while (!Thread.currentThread().isInterrupted()) {
                        try {
                            log.info("当前状态为：{}", statusChangeEvent.getStatus());
                            log.info("当前状态为REMOTE：{}", eurekaClient.getInstanceRemoteStatus());
                            Thread.sleep(10000);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                ApplicationInfoManager.getInstance().unregisterStatusChangeListener(eurekaListener.getId());
                // 执行完成释放监听器
                eurekaListener = null;
            }
        };
        eurekaClient.getApplicationInfoManager().registerStatusChangeListener(eurekaListener);
    }
}